//
//  SLStatusPictureView.swift
//  0319iOSweiboDemo
//
//  Created by Tang on 16/3/25.
//  Copyright © 2016年 大天朝. All rights reserved.
//

import UIKit
import SDWebImage

class SLStatusPictureView: UICollectionView {
    //MARK: - 属性
    
    
    private let Identifier = "Identifier"
    
    
    var pictureURLs: [NSURL]? {
        didSet {
            //拿到需要显示的图片的数组后.根据图片的数量来计算配图需要的宽和高
           let size = calcViewSize()
            
            //自己来更新自己的宽度和高度
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            
            //当拿到pictureURLs 后.来根据pictureURLs的数量重新设置CollectionView
            self.reloadData()
        }
    }
    //根据图片的数量来计算配图需要的宽和高
    private func calcViewSize() -> CGSize {
        layout.itemSize = CGSize(width: SLStatusPictureCellWh, height: SLStatusPictureCellWh)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        let count = pictureURLs?.count ?? 0
        
        if pictureURLs?.count == 0 {
            layout.itemSize = CGSizeZero
            return CGSizeZero
        }
        //单张
        if pictureURLs?.count == 1 {
           var imageSize = CGSize(width: SLStatusPictureCellWh, height: SLStatusPictureCellWh)
            
            let urlString = pictureURLs![0].absoluteString
            
            //去本地获取对应图片的大小
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(urlString) {
                
                imageSize = image.size
//                SLPrint(msg: "一张图片大小: \(imageSize): \(urlString)")
            }
            
            //有些图片小
            if imageSize.width < 40 {
                imageSize.width = 40
            }
            
            //有些图片大
            if imageSize.width > UIScreen.width * 0.5 {
                imageSize.width = UIScreen.width * 0.5
            }
            layout.itemSize = CGSize(width: 160, height: 120)
            return layout.itemSize
        }
        //多张 默认3列
        layout.minimumInteritemSpacing = SLStatusPictureManager
        layout.minimumLineSpacing = SLStatusPictureManager
        
        let column = SLStatusPictureMaxCloumn
        //有些情况下2张
        if count == 2 || count == 4 {
            column == 2
        }
        
        //计算行数
        let row = (count + column - 1) / column
        
        //计算宽度 cell的宽度 * cell的列数 + (列数 - 1) * cell之间的间距
        let width = SLStatusPictureCellWh * CGFloat(column) + (CGFloat(column) - 1 ) * SLStatusPictureManager
        
        //计算高度 cell的高度 * cell的行数 + (行数 - 1) * cell之间的间距
        let height = SLStatusPictureCellWh * CGFloat(row) + (CGFloat(row) - 1 ) * SLStatusPictureManager
        return CGSize(width: width, height: height)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private let layout = UICollectionViewFlowLayout()
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        //默认是true .如果一个控制器view面面只有一个UIScrollView/子类.点击状态栏往上滚动
        self.scrollsToTop = false
        //配图视图设置数据源
        self.dataSource = self
        self.registerClass(SLStatusPictureViewCell.self, forCellWithReuseIdentifier: Identifier)
        self.backgroundColor = UIColor.clearColor()
    }
    
    
}
extension SLStatusPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Identifier, forIndexPath: indexPath) as! SLStatusPictureViewCell
        
//        cell.backgroundColor = UIColor.random()
        cell.imageURL = pictureURLs![indexPath.item]
        
        return cell
    }
}

//MARK: - 自定义cell
class SLStatusPictureViewCell: UICollectionViewCell {
    
    //MARK: - 属性
    var imageURL: NSURL? {
        didSet {
            //使用SDWebImage设置图片
            if let url = imageURL {
                bkgImageView.sd_setImageWithURL(url)
            }
            
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 懒加载
    //背景图片
   override init(frame: CGRect) {
        super.init(frame: frame)
    
        perparUI()
    }
    private func perparUI() {
        addSubview(bkgImageView)
        
        //添加约束
        bkgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
            
            // 设置bkgImageView的内容填充模式
            bkgImageView.contentMode = UIViewContentMode.ScaleAspectFill
            
            //超出imageView的减掉
            bkgImageView.clipsToBounds = true
        }
    }
   
    private lazy var bkgImageView: UIImageView = UIImageView()
}
